<template>
  <div class="userManagement-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="24">
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleCreateCourseIntelligent"
        >
          智能排课
        </el-button>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleUpdateCourse"
        >
          人工排课
        </el-button>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleUpdateStudent"
        >
          安排学生
        </el-button>
        <el-button icon="el-icon-delete" type="danger" @click="handleDelete">
          批量删除
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-left-panel :span="24">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item label="班级名称">
            <el-input
              v-model.trim="queryForm.className"
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="课程类型">
            <CourseTypeSelector v-model="queryForm.courseTypeId" />
          </el-form-item>
          <el-form-item label="选择教师">
            <el-select
              v-model="queryForm.teacherId"
              placeholder="请选择教师"
              clearable
            >
              <el-option
                v-for="item in teacherList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学生名字">
            <el-input
              v-model.trim="queryForm.stuName"
              placeholder="请输入学生名字"
              clearable
            />
          </el-form-item>
          <el-form-item label="选择日期">
            <el-date-picker
              v-model="queryForm.courseDay"
              type="daterange"
              clearable
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="handleQueryData"
            >
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="courseList"
      :element-loading-text="elementLoadingText"
      @selection-change="setSelectRows"
    >
      <el-table-column show-overflow-tooltip type="selection"></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="id"
        label="id"
        width="80"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="infoClass.className"
        label="班级名称"
        width="150"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="infoCourseType.className"
        label="课程类型"
        width="100"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="teacher.name"
        label="教师"
        width="100"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="infoClassroom.name"
        label="教室"
        width="120"
      ></el-table-column>
      <el-table-column show-overflow-tooltip label="学生">
        <template #default="{ row }">
          {{ row.students && row.students.map((d) => d.name).join(', ') }}
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="startDate"
        label="开始时间"
        width="150"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="endDate"
        label="结束时间"
        width="150"
      ></el-table-column>
      <el-table-column show-overflow-tooltip label="操作" width="100">
        <template #default="{ row }">
          <el-button type="text" @click="handleUpdateCourse(row)">
            编辑
          </el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :page-size="queryForm.pageSize"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <CourseEditor ref="courseEditor" @on-success="handleQueryData" />

    <IntelligentCourseCreator
      ref="intelligentCourseCreator"
      @on-success="handleQueryData"
    />

    <StudentManage ref="studentManage" @on-success="handleQueryData" />
  </div>
</template>

<script>
  import { format } from 'date-fns'
  import { getCourseByPage, deleteCourse } from '@/apis/course'
  import { getTeacherByPage } from '@/apis/teacher'
  import CourseTypeSelector from '@/components/Selector/CourseTypeSelector'
  import CourseEditor from '@/components/CourseEditor'
  import IntelligentCourseCreator from '@/components/IntelligentCourseCreator'
  import StudentManage from './components/StudentManage'

  export default {
    components: {
      CourseTypeSelector,
      CourseEditor,
      IntelligentCourseCreator,
      StudentManage,
    },
    data() {
      return {
        courseList: null,
        teacherList: [],
        courseTypeList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        elementLoadingText: '正在加载...',
        queryForm: {
          pageNum: 1,
          pageSize: 20,
          className: null,
          courseTypeId: null,
          teacherId: null,
          studentName: null,
          courseDay: [],
        },
      }
    },
    created() {
      getTeacherByPage().then(({ list }) => {
        this.teacherList = list
      })
      this.fetchData()
    },
    methods: {
      setSelectRows(val) {
        this.selectRows = val
      },
      handleCreateCourseIntelligent(row) {
        this.$refs['intelligentCourseCreator'].showEdit()
      },
      handleUpdateCourse(row) {
        if (row.id) {
          this.$refs['courseEditor'].showEdit(row)
        } else {
          this.$refs['courseEditor'].showEdit()
        }
      },
      handleUpdateStudent() {
        this.$refs['studentManage'].showEdit()
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            await deleteCourse([row.id])
            this.$baseMessage('操作成功', 'success')
            this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id)
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              await deleteCourse(ids)
              this.$baseMessage('操作成功', 'success')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      handleQueryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const {
          pageNum,
          pageSize,
          className,
          courseTypeId,
          teacherId,
          stuName,
          courseDay,
        } = this.queryForm

        const data = {
          pageNum,
          pageSize,
          className,
          courseTypeId,
          teacherId,
          stuName,
        }

        if (courseDay && courseDay.length > 0) {
          data.startDate = format(new Date(courseDay[0]), 'yyyy-MM-dd 00:00:00')
          data.endDate = format(new Date(courseDay[1]), 'yyyy-MM-dd 23:59:59')
        }
        const { list, total } = await getCourseByPage(data)
        this.courseList = list
        this.total = total
        setTimeout(() => {
          this.listLoading = false
        }, 300)
      },
    },
  }
</script>
